<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <van-cell v-for="(item,index) in list" :key="index" :title="item.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResultsAPI } from '../../../api/index.js'
export default {
  name: 'SearchResult',
  props: {
    searchInput: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      list: [],
      page: 1, // 当前翻页页码
      per_page: 10, // 每页数据容量
      loading: false, // 控制加载中的loading状态
      finished: false, // 控制数据加载结束状态
      error: false // 控制列表加载失败的提示状态
    }
  },
  methods: {
    async onLoad () {
      try {
        const res = await getSearchResultsAPI({
          q: this.searchInput,
          per_page: this.per_page,
          page: this.page
        })
        console.log(res)
        this.list.push(...res.data.data.results)
        this.loading = false

        if (res.data.data.results.length === 0) {
          this.finished = true
        } else {
          // 进行翻页操作
          this.page++
        }
      } catch (error) {
        console.log(error)
        this.error = true
        this.loading = false
      }
    }

    // onLoad () {
    //   // 异步更新数据
    //   // setTimeout 仅做示例，真实场景中一般为 ajax 请求
    //   setTimeout(() => {
    //     for (let i = 0; i < 10; i++) {
    //       this.list.push(this.list.length + 1)
    //     }

    //     // 加载状态结束
    //     this.loading = false

    //     // 数据全部加载完成
    //     if (this.list.length >= 40) {
    //       this.finished = true
    //     }
    //   }, 1000)
    // }
  }
}
</script>

<style scoped lang="less">
.search-result{
  height: 91vh;
  overflow-y: auto;
}
</style>
